/**
 * 装修首页
 */
import {
  util,
  api,
  storage,
} from '../js/util'
import {
  cart
} from '../js/modules/order';

import authorize from '../js/modules/authorize'

import {
  config,share
} from "../js/modules/gloab";
import {
  router,
  pagesInfo
} from '../js/router.js'
import BasePage from '../js/common/base-page'
import { isEmpty, throttle } from '../js/newUtil';
import { getStorageSync, hideTabbar, setStorageSync } from '../js/compatible';
import {
  theme
} from '../js/modules/theme'

const app = getApp()

BasePage({
  pageKey: "index",
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    timer: null,
    time: null, //加载时时间缀
    loopDnsCount: 0, //DNS循环数量
    loopVisitCount: 0, //visit循环数量
    visitTimer:null,
    isShowAdvert:false,    //是否展示插屏广告
    showDialog:false,    //是否显示遮罩层
    showLive:false,  //显示直播
    showMinService:false,  //显示客服
    showPhone:false,  //显示电话
    phone:'',  //电话号码
    isIphoneX:app.globalData.isIphoneX,
    mainColor:'',//主题色
    Currency:'',//货币符号
    NoLoginShowPrice:false,//
    GoodsUnitDisplayMode:0,
    FrontShowStockDetail:false,
    LoginType:0,//登录方式
    isLogin:true,//判断是否登录
    advertNum:0,//插屏
    height:0,
    CartName:'',
    listState:true,
    tabindex:-1,
    curPath:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    app.initTabBar();
    var h = wx.getSystemInfoSync().windowHeight;
    this.setData({
      height:h
    })
    let role=storage.get("LoginSessionRoleKey")||"store";
    if(role&&(role=="supplier"||role=="clerk"||role=="vendor")){
      router.redirect({
        path: pagesInfo.login.url+"?role="+role
      });
      return;
    }
    this.indexWidgetsComponent = this.selectComponent("#indexWidgetsComponent")
    this.giftPacks = this.selectComponent("#giftPacks");
    this.advertPacks = this.selectComponent("#advertPacks");
    //加载配置
    this.getIndexPageConfig()
    this.getWholesaleConfig(function(model){
      if (that.advertPacks) {
        that.advertPacks.getAdverScreen();
      }
      that.indexWidgetsComponent.setData({
        quantityDigits: model.QuantityDigits,
        priceDigits: model.PriceDigits,
        enableZeroStockBuy: model.EnableZeroStockBuy,
        NotShowProductNoneOffered: model.NotShowProductNoneOffered, // 是否不显示无货商品按钮
        spectStyle: model.GoodsDisplayMode,
        isScanty: model.IsScanty, //是否允许缺货登记
        addressAssignDepot: model.AddressAssignDepot,//收货地区匹配仓库
        showShareShadow:that.data.showDialog,
        NoLoginShowPrice:model.NoLoginShowPrice,//0：建议零售价 1：不显示价格
        CartName:api.CartName,
        GoodsUnitDisplayMode:model.GoodsUnitDisplayMode,
        FrontShowStockDetail:model.FrontShowStockDetail,
        BGColorForMobile: model.BGColorForMobile
      });
    });
    this.getShareInfo();
    this.getFace()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    setStorageSync('tabindex', -1)
    let pages = getCurrentPages();
    let curPage = pages[pages.length-1];
    let curPath = curPage.__route__;
    if(curPath.indexOf('/')!=0){
      curPath = '/'+curPath;
    }
    //隐藏原生底部导航
    hideTabbar()
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex,
      curPath:curPath
    })
    if (this.indexWidgetsComponent==null) return; 
    this.isCanVisit(()=>{
      //是否显示分享遮罩层
      let showDialog = app.globalData.indexShowDialog;
      this.setData({
        showDialog:showDialog
      });
      app.globalData.indexShowDialog = false;
      //退出重新登录后，要重新加载或者pageWidgets==0也要重新加载
      if ((app.dns.proprietorId > 0 && app.dns.fkFlag != app.dns.proprietor && this.indexWidgetsComponent.data.widgets.length == 0) || app.globalData.index.isReload) {
        this.indexWidgetsComponent.initPropertity(app.dns.fkFlag == app.dns.proprietor);
        this.indexWidgetsComponent.loadTemplates();
      }
      //如果域名解析没有请求完，则等待
      else if (app.dns.fkId == 0 || (app.dns.fkId > 0 && app.dns.proprietorId == 0)) {
        this.check_dns_analysis();
      } else if (app.dns.proprietorId > 0 && this.indexWidgetsComponent.data.widgets.length == 0) {
        this.indexWidgetsComponent.loadTemplates();
      } else {
        //加载完后页面之前的切换，需要重新加载数量
        // this.indexWidgetsComponent.loadProductQuantity();
        //获取购物车数量
        // this.completeCallBack();
      }
      if(authorize.isLogin('store')){
        cart.get_cart_count();
      }
      this.setData({
        mainColor:api.titleColor||"#e56b14",
        Currency:api.Currency || '￥',
        isLogin:authorize.isLogin('store')
      });
    })
    var info = storage.get('index_template_data_0');
    // console.log(info,'=========info');
    var that = this;
    if(info.length > 0){
      var data = {
        pageId:info[1].PageId,
        PublishTime:info[1].PublishTime
      };
      config.indexCompare(data,function(content){
        if(content.Success){
          that.indexWidgetsComponent.initPropertity(false);
          that.indexWidgetsComponent.loadTemplates();
          wx.stopPullDownRefresh();
        }
      })
    }
  },
  onNoticeParent(){
    //加载大礼包
    if (this.giftPacks) {
      this.giftPacks.getCouponGift(this.data.LoginType);
    }
  },
  isCanVisit(callback){
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(()=>{
      if(api.isLoginVisit!=undefined){
        that.data.loopVisitCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit&&!authorize.isLogin('store'))) {
          authorize.redirect('store');
        }else{
          callback();
        }
      }else if (that.data.loopVisitCount < 60) {
        that.data.loopVisitCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer(){
    if (this.data.visitTimer!=null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig(callback) {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function(model) {
        //获取直播、客服显示与否
        that.setData({
          showLive:model.IsShowLive,
          showMinService:model.IsShowMinService,
          showPhone:model.IsShowPhone,
          phone:model.ServicePhone,
          IsShowJizhipai:model.IsShowJizhipai,
          distributorCustomNo:model.distributorCustomNo,
          LoginType: model.LoginType || 0
        }, () => {
          if (callback && typeof (callback) == "function") {
            callback(model);
          }
        });
        // 获取缓存的主题色，并设置缓存
        try {
          setStorageSync('configTitleColor', model.TitleColorForMobile)
          api.titleColor = model.TitleColorForMobile
        } catch (e) {
          api.titleColor = model.TitleColorForMobile
        }
        wx.setNavigationBarTitle({
          title: model.SiteName
        });
        wx.setNavigationBarColor({
          backgroundColor: model.TitleColorForMobile,
          frontColor: '#ffffff',
        });
      });
  },
  getIndexPageConfig () {
    let that = this
    theme.getIndexPageConfig(0, function (res) {
      that.indexWidgetsComponent.setData({
        indexPageBackground: res.BGColor || '' // 首页内设置的背景颜色
      })
    })
  },
  /**
   * 检测dns和分析
   */
  check_dns_analysis: function() {
    let that = this;
    this.clearDnsTimer();
    this.data.timer = setTimeout(function() {
      if (app.dns.fkId > 0 && that.indexWidgetsComponent.data.widgets.length == 0) {
        that.indexWidgetsComponent.initPropertity();
        that.indexWidgetsComponent.loadTemplates();
        that.data.loopDnsCount = 0;
      }else if(that.data.loopDnsCount < 60){
        that.data.loopDnsCount++;
        that.check_dns_analysis();
      }
    }, 100);
  },
  clearDnsTimer(){
    if (this.data.timer!=null) {
      clearTimeout(this.data.timer);
      this.data.timer = null;
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() { 
    this.data.loopDnsCount = 0;
    this.data.loopVisitCount = 0;
    this.clearDnsTimer();
    this.clearVisitTimer();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.indexWidgetsComponent.initPropertity(false);
    this.indexWidgetsComponent.loadTemplates();
    this.getFace()
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.indexWidgetsComponent.loadMorePageWidgets();
  },
  /**
   * 获取分享信息
   */
  getShareInfo:function(){
    let that = this;
    let param = {
      Proprietor:app.dns.proprietor,
      ProprietorId:app.dns.proprietorId,
      Type:'mall'
    }
    share.getinfo(param,false,function(res){
      let shareObj = {};
      shareObj.title = res.Title || "邀请加入";
      shareObj.img = res.ImgSrc!=''?api.imgDomain+res.ImgSrc:''; //.replace('http://','https://')
      that.setData({
        shareObj:shareObj
      })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let storeInfo = authorize.getEntity();
    let scene="";
    if(storeInfo){
      scene=storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    }   
    let path = pagesInfo.index.url + `?scene=${scene}`;
    let {shareObj} = this.data;
    return {
      title: shareObj.title,
      imageUrl:shareObj.img,
      path: path
    }
  },
  /**
   * 分享朋友圈（beta版本，仅限安卓手机）
   */
  onShareTimeline:function(){
    let storeInfo = authorize.getEntity();
    let scene="";
    if(storeInfo){
      scene=storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    }   
    let {shareObj} = this.data;
    return {
      title: shareObj.title,
      imageUrl:shareObj.img,
      query: 'scene='+scene
    }
  },
  onCloseAdvert:function(){
    this.setData({
      isShowAdvert:false
    })
  },
  completeCallBack: throttle(function (){
    console.log('加载广告')
    //加载广告
    if (this.advertPacks) {
      this.advertPacks.getAdverScreen();
    }
    //获取购物车数量
    cart.get_cart_count();
  }, 2000),
  bindCurrent(e){
    var tabindex = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      this.setData({ tabindex: tabindex });
    }
    app.onChangeTabBar(e);
  },
    /**
   * 获取用户头像
   * 
   * 在首页用此接口是为了获取到用户当前是否存在登录异常信息
   * 
   * 如果存在则提示用户
   */
  getFace() {
    let dns = app.dns || {}
    if (isEmpty(dns)) {
      return
    }
    var data = {
      proprietor: dns.proprietor || '',
      proprietorId: dns.proprietorId || '',
    }
    config.getAvatar(data, function (res) {
      if (!res.Success) {
        util.alert(res.Message)
      }
    })
  },
})